package com.itheima.springbootwebtlias.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.mapper.StudentMapper;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.pojo.Student;
import com.itheima.springbootwebtlias.pojo.StudentQueryParam;
import com.itheima.springbootwebtlias.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;


    @Override
    public PageResult page(StudentQueryParam queryParam) {
        //1.启动分页插件
        PageHelper.startPage(queryParam.getPage(),queryParam.getPageSize());

        //1.2 调用分页插件增强的持久层方法
        Page<Student> page = (Page<Student>) studentMapper.selectByCondition(queryParam);

        //1.3 从分页插件增强方法的返回结果中，获取数据封装到PageResult对象中
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    @Override
    public List<Student> selectAll() {
        List<Student> students = studentMapper.selectAll();

        return students;
    }

    // 添加学员
    @Transactional
    @Override
    public void saveStudent(Student student) {

        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        studentMapper.insert(student);

    }

    //批量删除
    @Override
    public void removeBatch(List<Integer> ids) {
        //1.调用持久层Mapper，批量删除学员信息
        studentMapper.deleteBatchById(ids);


    }

    //更新学员信息/修改学员
    @Override
    @Transactional
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    //根据id查询学员信息
    @Override
    public Student queryById(Integer id) {
        Student  student = studentMapper.selectById(id);
        return student;
    }

    //违纪处理
    @Override
    public void violation(Integer id, Integer score) {
        Student student = studentMapper.selectById(id);
        student.setViolationScore(student.getViolationScore()+score);
        student.setViolationCount(student.getViolationCount()+1);
        studentMapper.update(student);
        log.info("student:{}",student);
    }


}
